package com.h3bpm.web.engineEvent;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

/**
 * 自定义http类
 *
 */
public class HttpLocalUtils {

    private static Logger logger  = Logger.getLogger(HttpLocalUtils.class);

    /**
     * HTTP发送post、put请求，带header、body的方法，获取结果
     * @param url
     * @param requestMethod POST、PUT
     * @param headerMap
     * @param
     * @author yswKnight
     * @return
     */
    public static String httpRequest(String url, String requestMethod, Map<String, String> headerMap, String params) {
        logger.info("<><><>进入http请求工具包。。 url:"+url);
        String result = "";
        HttpURLConnection connection = null;
        BufferedReader in = null;
        OutputStreamWriter outer = null;
        InputStream ips = null;
        StringBuffer buffer = null;

        try {
            URL restURL = new URL(url);
            connection = (HttpURLConnection) restURL.openConnection();
            connection.setRequestMethod(requestMethod);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            //循环增加header
            Iterator headerIterator = headerMap.entrySet().iterator();
            while(headerIterator.hasNext()){
                Map.Entry<String,String> elem = (Map.Entry<String, String>) headerIterator.next();
                connection.setRequestProperty(elem.getKey(),elem.getValue());
            }

            outer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            outer.write(params);
            outer.flush();
            outer.close();
            logger.info("<><><>读取参数结束");

            connection.connect();
            ips = connection.getInputStream();
            logger.info("打印读取流：{}"+ips);
            System.out.println("new String(ips) = " + ips.toString());

            in = new BufferedReader(new InputStreamReader(ips, "UTF-8"));
            buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
                buffer.append("\r\n");
                logger.info("读取参数：{}"+line);
            }
            in.close();
            ips.close();
            //得到结果
            result = buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            connection.disconnect();
        }
        return result;
    }



    public static String doPost(String url,String json){
        PostMethod post = null;
        try {

            HttpClient httpclient = new HttpClient();
            post = new PostMethod(url);
            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
            post.addRequestHeader("Content-Type", "application/json;charset=utf-8");
            post.setRequestEntity(new ByteArrayRequestEntity(json.getBytes("UTF-8")));
            httpclient.executeMethod(post);
            return new String(post.getResponseBody(), "utf-8");

        } catch (IOException e) {
            logger.info("doPost请求异常"+e.getMessage());
            e.printStackTrace();
            return null;
        }finally {
            post.releaseConnection();
        }

    }


    public static String doPut(String url,String json){
        PutMethod put = null;
        try {
            HttpClient httpclient = new HttpClient();
            put = new PutMethod(url);
            put.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
            put.addRequestHeader("Content-Type", "application/json;charset=utf-8");
            put.setRequestEntity(new ByteArrayRequestEntity(json.getBytes("UTF-8")));
            httpclient.executeMethod(put);
            return new String(put.getResponseBody(), "utf-8");
        } catch (IOException e) {
            logger.info("doPut请求异常"+e.getMessage());
            e.printStackTrace();
            return null;
        }finally{
            put.releaseConnection();
        }
    }


}
